library(graphics)

# Question B.
fB <- function(x){
  return ((x*x*x + 4*x*x + 3*x + 5) / (2*x*x*x - 9*x*x + 18*x -2))
}

curve(fB, 0, 4, 200, bty = "l", xlab = "x", ylab = "y", col = "red")
curve(x*x*x + 4*x*x + 3*x + 5, 0, 4, 200, add = TRUE, bty = "l",
      xlab = "x", ylab = "y", col = "green")
curve(2*x*x*x - 9*x*x + 18*x -2, 0, 4, 200, add = TRUE, bty = "l",
      xlab = "x", ylab = "y", col = "blue")
abline(h=0)

legend(x = 'topright', 
       text.width = NULL, 
       legend = c("y = (x^3 + 4x^2 + 3x + 5) / (2x^3 - 9x^2 + 18x -2)",
                  "y = x^3 + 4x^2 + 3x + 5",
                  "y = 2x^3 - 9x^2 + 18x -2"),
       lty = c(1, 1, 1),
       col = c('red', "green", "blue"),
       bty = 'l',
       horiz = F)

# Question C.
x <- seq(-1, 12, length.out=600)
y <- vector()
for(t in x){
  y <- append(y, tan(t))
}
plot(x, y, xlim = c(-1,12), ylim = c(-1,12), xlab = "x", ylab = "y",
     col="blue", type = "l")
curve(1*x, -1, 12, 400, add = TRUE, bty = "l", xlab = "x", ylab = "y", col = "red")
abline(h=0)
legend(x = 'topright', 
       text.width = NULL,
       legend = c("y=x", "y=tan(x)"),
       lty = c(1, 1),
       col = c('red', "blue"),
       bty = 'l',
       horiz = F)

# Question D(1)
curve(sin(x/2)-1, -1, 18, 1000,ylim=c(-3,1), xlab = "x", ylab = "y",
      col="blue", main="y=sin(x/2)-1", bty="l")
abline(h=0)

# Question D(2)
curve(exp(x)-tan(x), -4, 3, 800, ylim=c(-3,5), xlab="x", ylab="y",
      col="blue", bty="l", main="y=e^x-tan(x)")
abline(h=0)

# Question D(3)
curve(x*x*x-12*x*x+3*x+1, -3, 12, 400, xlab="x", ylab="y",
      col="blue", bty="l", main="y=x^3-12x^2+3x+1")
abline(h=0)


# Question F1
AnglePi <- function(x){
  return (x * pi / 180)
}

fun <- function(x){
  l <- 89
  h <- 49
  D <- 55
  beta <- AnglePi(11.5)
  t <- AnglePi(x)
  A <- l * sin(beta)
  B <- l * cos(beta)
  C <- (h+0.5*D) * sin(beta) - 0.5 * D * tan(beta)
  E <- (h+0.5*D) * cos(beta) - 0.5 * D
  return (A*sin(t)*cos(t) + B*sin(t)*sin(t) - C*cos(t) - E*sin(t))
}

curve(fun, 0, 90, 5000, xlab="x", ylab="y",
      col="blue", bty="l", main="y=f(x) for Question F.")
abline(h=0)


# Question F2
curve(fun, -200, 200, 10000, xlab="x", ylab="y",
      col="blue", bty="l", main="y=f(x) for larger scale")
abline(h=0)

a1 <- fun(85)
b1 <- fun(80)
a2 <- fun(88)
b2 <- fun(86)

fun1 <- function(x){
  return ((a1-b1)*(x-85)/5+a1)
}

fun2 <- function(x){
  return ((a2-b2)*(x-88)/2+a2)
}

curve(fun1, -200, 200, 10000, add = TRUE,
      col="red", lty=2)
curve(fun2, -200, 200, 10000, add = TRUE,
      col="purple", lty=2)

legend(x = 'topright', 
       text.width = NULL,
       legend = c("y=f(x)", "第一次改变初值的割线y1",
                  "第二次改变初值的割线y2"),
       lty = c(1, 2, 2),
       col = c("blue", "red", "purple"),
       bty = 'l',
       horiz = F)

